package com.cmcc.aregister.cs.http;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;

import android.os.Handler;
import android.util.Log;

import com.cmcc.aregister.cs.cache.CacheManager;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.util.JsonParse;

/**
 * 
 * @author swq
 * 
 */
public class HttpAsyncTask extends BaseTask implements Runnable {
	private static final String TAG = "HttpAsyncTask";
	// 缓存类型
	public static final int CACHE_TYPE_SAVE = 2; // 保存map
	public static final int CACHE_TYPE_ACTION = 3; // 不保存map，action请求

	private int _httpMethod = GET;
	private String _httpUri = "";
	private int _jsonParseType;
	public int _cacheType;
	public boolean isNeedUpadteCache = true;
	public boolean isNotifyUI = true;
	public boolean isShow = true;
	public boolean isJsonParams = false;
	private String params;

	public int get_jsonParseType() {
		return _jsonParseType;
	}

	public void set_jsonParseType(int _jsonParseType) {
		this._jsonParseType = _jsonParseType;
	}

	public HttpAsyncTask(int httpMethod, int jsonParseType, String httpUri,
			int cacheType, boolean isShow) {
		this._httpMethod = httpMethod;
		this._httpUri = httpUri;
		this._jsonParseType = jsonParseType;
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "_jsonParseType:" + _jsonParseType);
		}
		this._cacheType = cacheType;
		this.isShow = isShow;
	}

	public HttpAsyncTask(int httpMethod, int jsonParseType, String httpUri,
			String params, int cacheType, boolean isShow) {
		this._httpMethod = httpMethod;
		this._httpUri = httpUri;
		this.params = params;
		this._jsonParseType = jsonParseType;
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "_jsonParseType:" + _jsonParseType);
		}
		this._cacheType = cacheType;
		this.isShow = isShow;
	}

	public HttpAsyncTask(int jsonParseType, String httpUri, String params,
			int cacheType, boolean isShow, boolean isJsonParams) {
		this._httpUri = httpUri;
		this.params = params;
		this._jsonParseType = jsonParseType;
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "_jsonParseType:" + _jsonParseType);
		}
		this._cacheType = cacheType;
		this.isShow = isShow;
		this.isJsonParams = isJsonParams;
	}

	@Override
	public void run() {
		try {
			get();
		} catch (HttpResponseException e) {
			exceptionHandle("HttpResponseException", e);
		} catch (ClientProtocolException e) {
			exceptionHandle("ClientProtocolException", e);
		} catch (IOException e) {
			exceptionHandle("IOException", e);
		} catch (NullPointerException e) {
			exceptionHandle("NullPointerException", e);
		} catch (Exception e) {
			exceptionHandle("Exception", e);
		}
	}

	/**
	 * Http获取数据核心方法
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws HttpResponseException
	 */
	private void get() throws HttpResponseException, ClientProtocolException,
			IOException {
		logger.d("run HttpAsyncTask get");
		byte[] _httpResponseData;
		Map<String, Object> _dataMapResult;
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "_jsonParseType:" + _jsonParseType + "_httpUri-->"
					+ _httpUri);
		}
		if (_httpMethod == POST && params != null) {
			_httpResponseData = HttpConnection.getHttpConnection()
					.doHttpPostRequest(_httpUri, params);
		} else if (isJsonParams) {
			_httpResponseData = HttpConnection.getHttpConnection()
					.doHttpPostRequestByJson(_httpUri, params);
		} else {
			_httpResponseData = HttpConnection.getHttpConnection()
					.doHttpRequest(_httpMethod, _httpUri);
		}
		params = null;
		_dataMapResult = JsonParse.parseJSON(_httpResponseData, _jsonParseType);
		logger.d("return map--------" + _dataMapResult);
		if (_cacheType == CACHE_TYPE_SAVE) {
			CacheManager.getInstance().saveCache(_httpUri, _dataMapResult);
		}
		if (isNotifyUI) {
			onReturnData(_dataMapResult);
		}
	}

	@Override
	public void onReturnData(Object result) {
		notifyUIObject(TASK_NOTIFY_RETURN_DATA, result);
	}

	@Override
	public void notifyUIObject(int what, Object obj) {
		if (_uiHandler != null) {
			if (!_uiHandler.hasMessages(what, obj)) {
				_uiHandler.sendMessage(_uiHandler.obtainMessage(what, obj));
			}
		}
	}

	public void setTaskBindingHandler(Handler uiHandler) {
		this._uiHandler = uiHandler;
	}

	@Override
	public void onSaveCacheAndReturnData(Object result) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpdateCache(Object result) {
		// TODO Auto-generated method stub

	}

	@Override
	public void exceptionHandle(String what, Exception e) {
		logger.e("...---...--->>>>EXCEPTION catch : " + what + "...--->"
				+ e.getLocalizedMessage());
		logger.d("...---...--->>>>EXCEPTION url : " + _httpUri);
		notifyUIStatus(TASK_NOTIFY_CONNECTION_FAIL);
	}

	@Override
	public void notifyUIStatus(int what) {
		if (_uiHandler != null) {
			if (!_uiHandler.hasMessages(what)) {
				_uiHandler.sendEmptyMessage(what);
			}
		}
	}

	public int get_cacheType() {
		return _cacheType;
	}

	// public boolean onPreExecuteCheckCache() {
	// return false;
	// }

	public boolean onPreExecuteCheckCache() {
		Object obj = CacheManager.getInstance().checkCache(_httpUri);
		if (obj != null) {
			@SuppressWarnings("unchecked")
			Map<String, Object> objMap = (HashMap<String, Object>) obj;
			checkCacheUpdateTime(objMap);
			onReturnData(objMap);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检查是否需要发送请求（要求:5分钟内不重发请求）
	 * 
	 * @param objMap
	 */
	private void checkCacheUpdateTime(Map<String, Object> objMap) {
		String cacheTime = (String) objMap.get(Arguments.CACHE_TIME);
		long time = Long.valueOf(cacheTime);
		long temp = System.currentTimeMillis() - time;
		if (temp < 0) {
			temp = -temp;
		}
		if (temp < Arguments.updateCacheTimes) {
			isNeedUpadteCache = false;
		}
	}
}
